package com.lazar.module1.subject4

import akka.actor.{Actor, ActorRef, ActorSelection, ActorSystem, Props}

class AActor() extends Actor {

  //  //接收消息并进行处理
  //  override def receive: Receive = {
  //    case "start" =>
  //      println("start, ok!")
  //      println("我打")
  //      //      Thread.sleep(1000)
  //      val selection: ActorSelection = context.actorSelection("/user/BActor")
  //
  //      selection ! "我打"
  //    case x: Int =>
  //      println(s"厉害！佛山无影脚 第 $x 脚")
  //      val selection: ActorSelection = context.actorSelection("/user/BActor")
  //      selection ! x
  //  }
  var count = 0
  override def receive: Receive = {
    case "start" => {
      println("AActor 启动")
      println("stark ok")
      println("我打")
      //发给 BActor,actorof形式是创建（注册）一个新的actor对象，selection这种方式是获取之前创建好的actor,根据actorsystem自己path树
      val selection: ActorSelection = context.actorSelection("/user/BActor")
      selection ! "我打"
    }
    case "我打" => {
      count += 1
      println(s"AActor(黄飞鸿) 挺猛 看我佛山无影脚 第${count}脚")
      //      Thread.sleep(1000)
      val selection: ActorSelection = context.actorSelection("/user/BActor")
      selection ! "我打"
    }
  }

}

class BActor extends Actor {
  //  val rival:ActorRef = this.context.actorOf(Props[AActor], "AActor")
  println("BActor 初始化。。。。")
  var count = 0
  override def receive:Receive = {
    case "我打" => {
      count += 1
      println(s"BActor(乔峰) 厉害 看我降龙十八掌 第${count}掌")
      //      Thread.sleep(1000)
      sender() ! "我打"
      if (count==100){
        context.stop(self)
      }
    }
  }



}


object HelloActor {

  //通过ActorSystem创建线程池对象myFactory
  private val myFactory = ActorSystem("myFactory")
  //通过myFactory.actorOf来创建一个Actor
  private val bActorRef: ActorRef = myFactory.actorOf(Props[BActor], "BActor")
  private val aActor: ActorRef = myFactory.actorOf(Props[AActor], name = "AActor")

  def main(args: Array[String]): Unit = {
    println("AActor 出招了...")
    aActor ! "start"
    //让程序休眠100毫秒
    Thread.sleep(Integer.MAX_VALUE)


  }
}

